package net.gianrishandy.jbase.component;

import java.awt.Color;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.DecimalFormat;

import javax.swing.JTextField;

/**
 * @author Gian Rishandy
 *
 */
public class NumberField extends JTextField{
	
	private static final long serialVersionUID = 532396245573395729L;
	private String numberText;
	private int numberOfDecimal;
	private Color defaultColor;
	
	public NumberField() {
		numberOfDecimal = 2;
		numberText = "0";
		setText("0");
				
		setHorizontalAlignment(JTextField.RIGHT);
		addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent e) {
				if(defaultColor == null){
					defaultColor = getForeground();
				}				
				setText(numberText);
			}
			@Override
			public void focusLost(FocusEvent e) {
				format();
			}
		});
	}
	
	private void format(){
		try{
			numberText = getText();
			
			String lformat = "";
			
			for(int i=0;i<numberOfDecimal;i++){
				lformat = lformat + "0";
			}
			
			if(numberOfDecimal == 0){
				lformat = "###,###,###";
			}else{
				lformat = "###,###,###." + lformat;
			}			
			
			DecimalFormat df = new DecimalFormat(lformat);
			String text = df.format(Double.parseDouble(numberText));
			setText(text);
			setForeground(defaultColor);
		}catch(Exception e){
			setForeground(Color.red);
			requestFocus();
		}
	}
	
	/**
	 * Get integer value from NumberField
	 * 
	 * @return Integer
	 */
	public Integer getInteger(){
		return Integer.valueOf(numberText);
	}
	
	/**
	 * Get double value from NumberField
	 * 
	 * @return Double
	 */
	public Double getDouble(){
		return Double.valueOf(numberText);
	}
	
	/**
	 * Get String value from NumberField
	 * 
	 * @return
	 */
	public String getNumberText() {
		return numberText;
	}
	
	/**
	 * Set number as string on NumberField
	 * 
	 * @param numberText
	 */
	public void setNumberText(String numberText) {
		this.numberText = numberText;
	}
	
	/**
	 * Get number of decimal
	 * 
	 * @return Integer
	 */
	public int getNumberOfDecimal() {
		return numberOfDecimal;
	}
	
	/**
	 * Set number of decimal
	 * 
	 * @param numberOfDecimal
	 */
	public void setNumberOfDecimal(int numberOfDecimal) {
		this.numberOfDecimal = numberOfDecimal;
	}
}
